package com.example.mianshi;

import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class DoWorkTemplate {

    ExecutorService threadPool = Executors.newFixedThreadPool(10);

    ConcurrentLinkedQueue<MFile> queue = new ConcurrentLinkedQueue<MFile>();

    List<File> fileList = new ArrayList<File>();

    Map<String,MFile> treeMap = new TreeMap<String,MFile>(
            new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return Long.valueOf(o1).compareTo(Long.valueOf(o2));
                }
            }
    );
    CountDownLatch countDownLatch;

    protected void doWork(){
        long startTime = System.currentTimeMillis();

        //1寻找文件
        getFiles(getFilePath(),getFileSuffix());
        countDownLatch = new CountDownLatch(fileList.size() + 1);

        long getFilesTime = System.currentTimeMillis() - startTime;
        System.out.println("--------------------------------------getFilesTime :"+getFilesTime);
        //2多线程读文件
        for (File file : fileList) {
            threadPool.execute(new ReadFileThread(this,file));
        }
        //3多线程排序
        threadPool.execute(new SortFileThread(this));

        try {
            //线程处理完成关闭
            countDownLatch.await();
            threadPool.shutdownNow();
        } catch (Exception e) {
            e.printStackTrace();
        }

        long sortTime = System.currentTimeMillis() - startTime;
        System.out.println("--------------------------------------sortTime :"+sortTime);

        //输出
        int i = 1;
        for (Map.Entry<String, MFile> entry : treeMap.entrySet()) {
            System.out.println("last: count:"+ treeMap.size() + " mfile  " + entry.getValue().toString()+" ----" + i++);
        }

        long lastTime = System.currentTimeMillis() - startTime;
        System.out.println("--------------------------------------the work end" +lastTime);

    }

    protected abstract File getFilePath();

    protected abstract String getFileSuffix();

    public void getFiles(File file, String suffix){
        for (File f1 : file.listFiles()) {
            if(f1.isDirectory()){
                getFiles(f1,suffix);
            }else{
                if(f1.getName().endsWith(suffix)){
                    fileList.add(f1);
                }
            }
        }
    }
}
